package com.codingvip.str;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ThreeSum {


    /**
     * 思路
     * 标签：数组遍历
     * 首先对数组进行排序，排序后固定一个数 nums[i]nums[i]，再使用左右指针指向 nums[i]nums[i]后面的两端，数字分别为 nums[L]nums[L] 和 nums[R]nums[R]，计算三个数的和 sumsum 判断是否满足为 00，满足则添加进结果集
     * 如果 nums[i]nums[i]大于 00，则三数之和必然无法等于 00，结束循环
     * 如果 nums[i]nums[i] == nums[i-1]nums[i−1]，则说明该数字重复，会导致结果重复，所以应该跳过
     * 当 sumsum == 00 时，nums[L]nums[L] == nums[L+1]nums[L+1] 则会导致结果重复，应该跳过，L++L++
     * 当 sumsum == 00 时，nums[R]nums[R] == nums[R-1]nums[R−1] 则会导致结果重复，应该跳过，R--R−−
     * 时间复杂度：O(n^2)O(n
     * 2
     * )，nn 为数组长度
     * 例：-5，1，2，2，3，3，5
     *
     * @return
     */

    public static void main(String[] args) {
        int[] nums = new int[]{-5, 1, 2, 2, 3, 3, 5};
        int[] nums2 = new int[]{-1,0,1,2,-1,-4};
        int[] nums3 = new int[]{0,-4,-1,-4,-2,-3,2};
        int[] nums4 = new int[]{0,0,0};
        List<List<Integer>> result = ThreeSum.threeSum(nums4);
        System.out.println(result.iterator().toString());

    }

    public static   List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();
        if (nums == null || nums.length < 3) {
            return result;
        }
        Arrays.sort(nums);
        int low, high;
        for (int now = 0; now < nums.length; now++) {
            low = now + 1;
            high = nums.length - 1;
            if (nums[now] >0) {
                break;
            }
            if (now >= 1 && nums[now] == nums[now - 1]) {
                continue;
            }
            while (low < high) {
                if (nums[low] + nums[now] + nums[high] > 0) {
                    high = high - 1;
                } else if (nums[low] + nums[now] + nums[high] < 0) {
                    low = low + 1;
                } else {
                    if (highRepeat(nums, high)) {
                        high = high - 1;
                        continue;
                    }
                    if (lowRepeat(nums, low, now)) {
                        low = low + 1;
                        continue;
                    }

                    result.add(Arrays.asList(nums[now], nums[low], nums[high]));
                    high = high - 1;
                    low = low + 1;
                }
            }
        }
        return result;
    }

    private static boolean lowRepeat(int[] nums, int low, int now) {
        if (low > now + 1 && nums[low] == nums[low - 1]) {
            return true;
        }
        return false;
    }

    private static boolean highRepeat(int[] nums, int high) {
        if (high < nums.length - 1 && nums[high] == nums[high + 1]) {
            return true;
        }
        return false;
    }
}
